package Tests
{
	import Box2D.Collision.Shapes.b2PolygonShape;
	import Box2D.Collision.b2Collision;
	import Box2D.Collision.b2Manifold;
	import Box2D.Collision.b2WorldManifold;
	import Box2D.Common.Math.b2Math;
	import Box2D.Common.Math.b2Transform;
	import Box2D.Common.Math.b2Vec2;
	import Box2D.Common.b2Color;
	import Box2D.Common.b2Settings;
	
	import Framework.Test;
	
	public class PolyCollision extends Test
	{
		private var m_polygonA:b2PolygonShape = new b2PolygonShape;
		private var m_polygonB:b2PolygonShape = new b2PolygonShape;
		private var m_transformA:b2Transform = new b2Transform;
		private var m_transformB:b2Transform = new b2Transform;
		private var m_positionB:b2Vec2 = new b2Vec2;
		private var m_angleB:Number;
		
		public function PolyCollision()
		{
			super();
			{
				m_polygonA.SetAsBox(0.2, 10);
				m_transformA.Set(new b2Vec2(0, 10), 0.0);
			}
			
			{
				m_polygonB.SetAsBox(0.5, 0.5);
				m_positionB.Set(19.345284, 1.5632932);
				m_angleB = 1.9160721;
				m_transformB.Set(m_positionB, m_angleB);
			}
		}
		public override function Step():void{
			super.Step();
			
			var manifold:b2Manifold = new b2Manifold;
			b2Collision.CollidePolygons(manifold, m_polygonA, m_transformA, m_polygonB, m_transformB);
			
			var worldManifold:b2WorldManifold = new b2WorldManifold;
			worldManifold.Initialize(manifold, m_transformA, m_polygonA.radius, m_transformB, m_polygonB.radius);
			
			writeMessage('point count =' + manifold.pointCount);
			
			var i:int;
			var color:b2Color= new b2Color;
			{
				color.Set(0.9, 0.9, 0.9);
				var v:Vector.<b2Vec2> = new Vector.<b2Vec2>(b2Settings.b2_maxPolygonVertices);
				for (i = 0; i < m_polygonA.GetVertexCount(); ++i)
				{
					v[i] = b2Math.MulX(m_transformA,m_polygonA.vertices[i]);
				}
				m_debugDraw.DrawPolygon(v, m_polygonA.GetVertexCount(), color);
				
				for (i = 0; i < m_polygonB.GetVertexCount(); ++i)
				{
					v[i] = b2Math.MulX(m_transformB,m_polygonB.vertices[i]);
				}
				m_debugDraw.DrawPolygon(v, m_polygonB.GetVertexCount(), color);
			}
			
			color.Set(.9,.3,.3);
			for (i = 0; i < manifold.pointCount; ++i)
			{
				m_debugDraw.DrawPoint(worldManifold.points[i], 2, color);
			}			
		}
		public override function Key(code:String):void{
			switch(code){
				case 'a':
					m_positionB.x -= .1;
					break;
				case 'd':
					m_positionB.x += 0.1;
					break;				
				case 's':
					m_positionB.y -= 0.1;
					break;				
				case 'w':
					m_positionB.y += 0.1;
					break;				
				case 'q':
					m_angleB += 0.1 * Math.PI;
					break;				
				case 'e':
					m_angleB -= 0.1 * Math.PI;
					break;				
			}
			m_transformB.Set(m_positionB, m_angleB);
		}
	}
}